/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package im.node;
import im.general.Config;
import im.messages.BaseMessage;
import jade.core.AID;
/*import im.node.MobileNodeAgent;
import im.resources.ResourceStatus;
import im.resources.monitors.CPUMonitor;*/
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Gnaskky
 */
public class ClusterJoinReqBehaviour extends OneShotBehaviour {

    MobileNodeAgent mn = null;

    //CPUMonitor cpu = new CPUMonitor();

    public ClusterJoinReqBehaviour(MobileNodeAgent mn) {
        this.mn = mn;
    }

    /* NOTE: use this behaviour after GetCHList in a composite behaviour :) */
    public void action() {
        try {
            String newCH = mn.getBestCH();
            
            // if found a better CH (or NEW)
            if( mn.getClusterHeadID() == null || !mn.getClusterHeadID().equals(newCH)) {
                String join_type = (mn.getClusterHeadID() == null)? "NEW" : "UPD";
                if( this.mn.isShrinkJoin )
                    join_type = "SHR";

                System.out.println("[ClusterJoinReqBehav]\t" + join_type + " Join [MN CH]\t\t " + mn.getLocalName() + "\t" + newCH);
                /*
                getCHs();
                measure_CH_channel
                cli_CH = ES;
                if( Ch_size >= 1 )
                cli_CH = get_best_ch();
                 */
                //cli_CH.join_request(isNewJoin=true);g
                ACLMessage jreq_msg = new ACLMessage(ACLMessage.REQUEST);
                jreq_msg.addUserDefinedParameter(Config.IM_MSG_TYPE, Config.SRVC_JOIN_REQ_MSG);
                jreq_msg.addReceiver(new AID(newCH, AID.ISLOCALNAME));
                jreq_msg.setContentObject(mn.getMn_info());
                //System.out.println(jreq_msg.toString());
                this.mn.send(jreq_msg);
                
                // saves the CH
                this.mn.setClusterHeadID(newCH);
                this.mn.isShrinkJoin = false;
            }
        } catch (Exception ex) {
            Logger.getLogger(ClusterJoinReqBehaviour.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }

    }

}

